package cn.hebutrun.oulabot;

import cn.hebutrun.oulabot.common.config.OulaBotYamlConfig;
import cn.hebutrun.oulabot.common.util.ApiUtil;
import cn.hebutrun.oulabot.common.util.BotUtil;
import cn.hebutrun.oulabot.common.util.LogUtil;
import cn.hebutrun.oulabot.entity.enums.MessageTypeEnum;
import cn.hebutrun.oulabot.quartz.QuartzUtil;
import cn.hebutrun.oulabot.quartz.job.RemindLunchJob;
import cn.hebutrun.oulabot.service.IMessageService;
import cn.hebutrun.oulabot.websocket.BotClient;
import lombok.RequiredArgsConstructor;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.List;

@RequiredArgsConstructor
@SpringBootApplication
public class OulaBotApplication implements CommandLineRunner {

  //  private final MybatisPlusGenerator mybatisPlusGenerator;
  private final IMessageService iMessageService;
  private final Scheduler defaultScheduler;
  private final QuartzUtil quartzUtil;
  private final OulaBotYamlConfig oulaBotYamlConfig;
  private final ApiUtil apiUtil;

  public static void main(String[] args) {
    SpringApplication.run(OulaBotApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {
    //    mybatisPlusGenerator.generate();
    this.quartzInit();
    this.botInit();
  }

  private void botInit() {
    BotClient.connect(iMessageService, apiUtil);
    // 启动通知master
    List<String> master = oulaBotYamlConfig.getMaster();
    // 判断与主人是否为好友
    List<String> friendQQList = BotUtil.getFriendQQList();
    // 已加好友的发送通知
    master.retainAll(friendQQList);
    // 通知master
    master
        .forEach(
            qq ->
                BotUtil.sendMessage(
                    MessageTypeEnum.PRIVATE.getType(),
                    null,
                    Long.valueOf(qq),
                    "主人,机器人成功启动啦"));
  }

  private void quartzInit() throws SchedulerException {
    if (defaultScheduler.isShutdown()) {
      LogUtil.warn("quartz已关闭,执行重启...");
      defaultScheduler.start();
    }
    LogUtil.info("定时任务列表：" + defaultScheduler.getJobKeys(GroupMatcher.anyJobGroup()));
    quartzUtil.addQuartzJob(
        RemindLunchJob.class,
        new TriggerKey("remindLunch", "lunch"),
        "0 25 11 * * ? ",
        null,
        "每天中午提醒用餐",
        true);
  }
}
